package uk.ac.ebi.tm.luna.as;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.uima.UIMAFramework;
import org.apache.uima.aae.client.UimaAsBaseCallbackListener;
import org.apache.uima.aae.client.UimaAsynchronousEngine;
import org.apache.uima.adapter.jms.client.BaseUIMAAsynchronousEngine_impl;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.collection.CollectionReaderDescription;
import org.apache.uima.collection.EntityProcessStatus;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceConfigurationException;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceProcessException;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;
import org.uimafit.util.JCasUtil;

import uk.ac.ebi.tm.luna.type.Entity;
import uk.ac.ebi.tm.luna.type.Pmid;
import uk.ac.ebi.tm.luna.type.Roi;

public class MPClient {

    private static class CallbackListener extends UimaAsBaseCallbackListener {
        BufferedWriter bf

        public CallbackListener (BufferedWriter _bf) {
          bf = _bf
        }

        @Override
        public void entityProcessComplete(CAS cas, EntityProcessStatus aStatus) {
            try {
                JCas jcas = cas.getJCas();
                bf << jcas.getDocumentLanguage()

                jcas = jcas.getView("final")

                Iterator<Roi> roiIter = JCasUtil.iterator(jcas, Roi.class)

                // distinction for ROI not required at the moment
                // for now all annotations from ArticleTitle and AbstractText are combined
                while (roiIter.hasNext()) {
                  Roi roi = roiIter.next();
                  // println roi.getCoveredText()

                  Iterator<Entity> entityIter = JCasUtil.iterate(jcas, Entity.class, roi).iterator();
                  while (entityIter.hasNext()) {
                    Entity entity = entityIter.next();
                    // println entity
                    def ids = entity.getIds().toArray()
               
                    if ( !entity.category.equals("ma") && !entity.category.equals("hp") && !entity.category.equals("mp") ) {
                      if ( ids != null ) {
                        ids.each { id ->
                          bf << "\t"
                          bf << id
                        }
                      }
                    }
                  } 
                }

                bf << "\n"
     
            } catch (CASException e) {
                e.printStackTrace();
            }
        }
    }

    public static CollectionReader loadReader(String descriptorPath)
    throws IOException, InvalidXMLException,
    ResourceInitializationException {
        XMLInputSource descriptionIn = new XMLInputSource(descriptorPath);
        CollectionReaderDescription desc = UIMAFramework.getXMLParser()
        .parseCollectionReaderDescription(descriptionIn);
        CollectionReader reader = UIMAFramework.produceCollectionReader(desc);
        return reader;
    }

    public static void main(String[] args) {
        String inputf = args[0]
        def outf = new BufferedWriter(new FileWriter(new File(args[1])))

//        outf << "tttt\n"

        BaseUIMAAsynchronousEngine_impl asClient = new BaseUIMAAsynchronousEngine_impl();
        asClient.addStatusCallbackListener(new CallbackListener(outf));

        HashMap<String, Object> context = new HashMap<String, Object>();
        context.put(UimaAsynchronousEngine.ServerUri, "tcp://crunch:61616");
        context.put(UimaAsynchronousEngine.Endpoint, "anika_medline");
        context.put(UimaAsynchronousEngine.CasPoolSize, 10);
        context.put(UimaAsynchronousEngine.SerializationStrategy, "binary");

        try {
            CollectionReader medlineReader = loadReader("/homes/grabmuel/eclipse/luna/desc/reader/MedlineCollectionReaderDescriptor.xml");
            medlineReader.setConfigParameterValue("InputDirectory",inputf);
            medlineReader.reconfigure();

            // outf << "bbbbb\n"

            asClient.setCollectionReader(medlineReader);
            asClient.initialize(context);
            asClient.process();
            asClient.collectionProcessingComplete();
            asClient.stop();

            // outf << "cccc\n"

            outf.flush()
            outf.close()
        } catch (ResourceInitializationException e) {
            e.printStackTrace();
        } catch (ResourceProcessException e) {
            e.printStackTrace();
        } catch (InvalidXMLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ResourceConfigurationException e) {
            e.printStackTrace();
        }
    }
}
